package com.example.mall.dao;

import com.example.mall.model.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class TagDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insert(Tag tag) {
        String sql = "insert into tag (name) values (?)";
        try {
            jdbcTemplate.update(sql, tag.getName());
        }
        catch (Exception e) {

        }
    }

    public Tag getById(String id) {
        String sql = "select * from tag where id = ? lock in share mode";
        RowMapper<Tag> rowMapper = new BeanPropertyRowMapper<>(Tag.class);
        Tag tag = null;
        try {
            tag = jdbcTemplate.queryForObject(sql, rowMapper, id);
        }
        catch (Exception e) {
            return tag;
        }
        return tag;
    }

    public Tag getByName(String name) {
        String sql = "select * from tag where name = ? lock in share mode";
        RowMapper<Tag> rowMapper = new BeanPropertyRowMapper<>(Tag.class);
        Tag tag = null;
        try {
            tag = jdbcTemplate.queryForObject(sql, rowMapper, name);
        }
        catch (Exception e) {
            return tag;
        }
        return tag;
    }


}
